import React, { useState, useEffect } from 'react';
import { Button, Space, Modal, Tag, Row, Col, Card, Tooltip, Form, Input, Select, Pagination } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, EyeOutlined } from '@ant-design/icons';
import { vectorStore } from './store/vectorStore';
import { Vector, VectorStatus, } from './store/vectorTypes';
import VectorForm from './components/VectorForm';
import { useNavigate } from 'react-router-dom';

const { Option } = Select;

const VectorList: React.FC = () => {
  const navigate = useNavigate();
  const [vectors, setVectors] = useState<Vector[]>([]);
  const [editingVector, setEditingVector] = useState<Vector | null>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(12); // 每页显示1条数据
  const [filterForm] = Form.useForm();

  useEffect(() => {
    const fetchVectors = async () => {
      vectorStore.fetchModelOptions();
      let vectors = await vectorStore.fetchVectors();
      setVectors(vectors); // 创建新数组触发更新
    };
    fetchVectors();
  }, []);

  // 筛选条件
  const [filters, setFilters] = useState({
    name: '',
    baseType: undefined,
    status: undefined,
    vectorModel: '',
  });

  // 处理筛选
  const handleFilter = (values: any) => {
    setFilters(values);
    setCurrentPage(1); // 重置到第一页
  };

  // 处理分页变化
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  // 获取筛选后的数据
  const getFilteredData = () => {
    return vectors?.filter(vector => {
      return (
        (!filters.name || vector.name.toLowerCase().includes(filters.name.toLowerCase())) &&
        (!filters.baseType || vector.baseType === filters.baseType) &&
        (!filters.status || vector.status === filters.status) &&
        (!filters.vectorModel || vector.vectorModel.toLowerCase().includes(filters.vectorModel.toLowerCase()))
      );
    });
  };

  // 获取当前页的数据
  const getCurrentPageData = () => {
    const filteredData = getFilteredData();
    const startIndex = (currentPage - 1) * pageSize;
    return filteredData.slice(startIndex, startIndex + pageSize);
  };

  // 获取总数据量
  const getTotal = () => {
    return getFilteredData().length;
  };

  const handleCreate = () => {
    setIsModalVisible(true);
    setEditingVector(null); // 新建时清空编辑对象，防止交叉
    vectorStore.showCreateModal();
  };

  const handleEdit = async (vector: any) => {
    setIsModalVisible(true);
    let editingVector = await vectorStore.getVector(vector.id);
    setEditingVector(editingVector);
  };

  const handleDetail = (vector: Vector) => {
    navigate(`/engine/vector/${vector.id}`);
  };

  const handleDelete = (vector: Vector) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除向量知识库"${vector.name}"吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        vectorStore.deleteVector(vector.id);
        setVectors(vectors.filter(v => v.id !== vector.id));
      },
    });
  };

  const handleSubmit = (values: any) => {
    // 处理文件格式
    if (values.fileFormatArray) {
      values.fileFormat = values.fileFormatArray.join(',');
    }
    // 处理状态
    values.status = values.status ? VectorStatus.ENABLED : VectorStatus.DISABLED;
    // 处理可选字段，保证类型一致
    if (!values.indexType) values.indexType = undefined;
    if (!values.indexParams) values.indexParams = undefined;
    vectorStore.saveVector(values);
    setIsModalVisible(false);
  };

  const onCancel = () => {
    setIsModalVisible(false);
    setEditingVector(null);
  };


  const renderModel = (model: string) => {
    const modelMap = vectorStore.modelValues;
    const config = modelMap && modelMap[model as keyof typeof modelMap];
    return config ? <Tag color={config.color}>{config.title}</Tag> : <Tag>{model}</Tag>;
  };


  return (
    <div>
      {/* 筛选表单 */}
      <Card style={{ margin: '16px 0' }}>
        <Form
          form={filterForm}
          layout="inline"
          onFinish={handleFilter}
          initialValues={filters}
        >
          <Form.Item name="name" label="知识库名称">
            <Input placeholder="请输入知识库名称" allowClear />
          </Form.Item>
          <Form.Item name="baseType" label="知识库类型">
            <Select style={{ width: 120 }} allowClear placeholder="请选择类型">
              <Option value="text">文本</Option>
              <Option value="image">图片</Option>
              <Option value="mixed">混合</Option>
            </Select>
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select style={{ width: 120 }} allowClear placeholder="请选择状态">
              <Option value={VectorStatus.ENABLED}>启用</Option>
              <Option value={VectorStatus.DISABLED}>禁用</Option>
            </Select>
          </Form.Item>
          <Form.Item name="vectorModel" label="向量模型">
            <Select style={{ width: 120 }} allowClear placeholder="请选择向量模型">
              {vectorStore.modelOptions && vectorStore.modelOptions.map(model => (
                <Select.Option key={model.value} value={model.value}>
                  {model.title}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              搜索
            </Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate} style={{ marginLeft: 12 }}>
              新建知识库
            </Button>
          </Form.Item>
        </Form>
      </Card>

      <Row gutter={[24, 24]}>
        {getCurrentPageData().length === 0 ? (
          <Col span={24} style={{ textAlign: 'center', color: '#999' }}>暂无数据</Col>
        ) : (
          getCurrentPageData().map((vector) => (
            <Col xs={24} sm={12} md={8} lg={6} xl={6} key={vector.id}>
              <Card
                title={
                  <span style={{ fontWeight: 500 }}>
                    {vector.name}
                  </span>
                }
                onClick={() => handleDetail(vector)}
                extra={
                  <Space size={2}>
                    <Tooltip title="编辑">
                      <Button
                        type="text"
                        icon={<EditOutlined />}
                        onClick={e => {
                          e.stopPropagation();
                          handleEdit(vector);
                        }}
                      />
                    </Tooltip>
                    <Tooltip title="删除">
                      <Button
                        type="text"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={e => {
                          e.stopPropagation();
                          handleDelete(vector);
                        }}
                      />
                    </Tooltip>
                  </Space>
                }
                hoverable
                style={{ minHeight: 220 }}
              >
                <div style={{ marginBottom: 8 }}>
                  <Tag color={
                    vector.baseType === 'text' ? 'blue' :
                      vector.baseType === 'image' ? 'green' : 'purple'
                  }>
                    {vector.baseType === 'text' ? '文本' : vector.baseType === 'image' ? '图片' : '混合'}
                  </Tag>
                  <Tag color={vector.status === VectorStatus.ENABLED ? 'success' : 'default'}>
                    已{vector.status === VectorStatus.ENABLED ? '启用' : '禁用'}
                  </Tag>
                </div>
                <div><b>向量模型：</b>{renderModel(vector.vectorModel)}</div>
                <div><b>向量维度：</b>{vector.dimension}</div>
                <div><b>文件格式：</b>
                  {vector.fileFormat && vector.fileFormat.trim() !== '' && vector.fileFormat.split(',').map(format => (
                    <Tag key={format} style={{ marginRight: 4 }}>{format.toUpperCase()}</Tag>
                  ))}
                </div>
                <div><b>切片策略：</b>
                  <Tag color={
                    vector.splitStrategy === 0 ? 'blue' :
                      vector.splitStrategy === 1 ? 'green' : 'purple'
                  }>
                    {vector.splitStrategy === 0 ? '固定长度' :
                      vector.splitStrategy === 1 ? '语义分割' : '自定义'}
                  </Tag>
                </div>
                <div><b>知识库表数量：</b>{vector.itemCount}</div>
                {vector.description && (
                  <div>
                    <b>描述：</b>{vector.description}
                  </div>
                )}
                <div style={{ marginTop: 8, color: '#888' }}><b>创建时间：</b>{new Date(vector.createTime).toLocaleString()}</div>
              </Card>
            </Col>
          ))
        )}
      </Row>

      {/* 分页组件 */}
      <div style={{
        marginTop: 16,
        display: 'flex',
        justifyContent: 'flex-end',
        padding: '0 24px'
      }}>
        <Pagination
          current={currentPage}
          pageSize={pageSize}
          total={getTotal()}
          onChange={handlePageChange}
          showSizeChanger={false}
          showTotal={(total) => `共 ${total} 条`}
        />
      </div>

      <Modal
        title={editingVector ? '编辑向量知识库' : '新建向量知识库'}
        open={isModalVisible}
        onCancel={onCancel}
        footer={null}
        width={800}
        style={{ maxHeight: '80vh' }}
        bodyStyle={{
          maxHeight: 'calc(80vh - 108px)',
          overflowY: 'auto',
          padding: '24px'
        }}
      >
        <VectorForm
          initialValues={editingVector || undefined}
          onSubmit={handleSubmit}
          onCancel={onCancel}
        />
      </Modal>
    </div>
  );
};

export default VectorList; 